package com.study;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import javax.crypto.Cipher;
import java.nio.charset.Charset;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

/**
 * @Description: TODO
 * @Author: csc
 * @Date: 2024/4/15 16:44
 * @Version: 1.0
 **/
public class RsaTest {


    public static String  publicKey =
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDt0gstnt/4g7BmqM9pXPmddmzKGU9P9xpkn05oN5QdR5hkcw7YzqJicmbq/9TB1ZNIIOcIQijJriRK9aFYXquMmVsryFTM3QB0nv95kKgctssQ5Eg4K4Oc1k/DVvesmtpoh9uqOvb31j09JgScykJeoMNgLm0/gfvfc6AfgKy+xQIDAQAB";
    public static void main(String[] args) throws Exception {

      testBaseEncrypt();
    }


    public static void testBaseEncrypt() throws Exception {
        try {
            byte[] decoded = Base64.decode(publicKey);
            RSAPublicKey pubKey =
                    (RSAPublicKey)
                            KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
            // RSA加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            //**此处Base64编码，开发者可以使用自己的库**
            String outStr = new String(Base64.encode(cipher.doFinal("openapi@123.".getBytes("UTF-8"))));
            System.out.println(outStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
